<template>
	<el-main class="bg table_wrap">
		<!-- 统计图表区域 -->
		<el-row :gutter="20" style="margin-bottom: 20px;">
			<el-col :xs="24" :sm="12" :lg="12">
				<el-card shadow="hover">
					<div slot="header">
						<span>点赞趋势</span>
					</div>
					<line-chart 
						id="praiseTrendChart"
						:title="'点赞趋势'"
						:vm="praiseTrendData"
					></line-chart>
				</el-card>
			</el-col>
			<el-col :xs="24" :sm="12" :lg="12">
				<el-card shadow="hover">
					<div slot="header">
						<span>点赞状态分布</span>
					</div>
					<pie-chart 
						id="praiseStatusChart"
						:title="'点赞状态分布'"
						:list="praiseStatusData"
						type="点赞状态"
					></pie-chart>
				</el-card>
			</el-col>
		</el-row>

		<!-- 点赞排行榜 -->
		<el-row :gutter="20" style="margin-bottom: 20px;">
			<el-col :xs="24" :sm="24" :lg="24">
				<el-card shadow="hover">
					<div slot="header">
						<span>内容点赞排行榜</span>
					</div>
					<el-table :data="praiseRanking" border stripe max-height="300">
						<el-table-column type="index" label="排名" width="60" align="center"></el-table-column>
						<el-table-column prop="source_id" label="内容ID" min-width="100"></el-table-column>
						<el-table-column prop="source_table" label="类型" min-width="100"></el-table-column>
						<el-table-column prop="count" label="点赞数" min-width="100" sortable>
							<template slot-scope="scope">
								<el-tag type="success">{{ scope.row.count }}</el-tag>
							</template>
						</el-table-column>
					</el-table>
				</el-card>
			</el-col>
		</el-row>
		
		<!-- 搜索表单 -->
		<el-form label-position="right" :model="query" class="form p_4" label-width="120">
			<el-row>
				<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
					<el-form-item label="用户ID">
						<el-input-number v-model.number="query.user_id" :min="0"></el-input-number>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
					<el-form-item label="点赞时间">
						<el-date-picker
							v-model="query.date_range"
							type="daterange"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							value-format="yyyy-MM-dd">
						</el-date-picker>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="24" :lg="24" class="search_btn_wrap">
					<el-col :xs="24" :sm="12" :lg="12" class="search_btn_1">
						<el-form-item>
							<el-button type="primary" @click="search()" class="search_btn_find">查询</el-button>
							<el-button @click="reset()" class="search_btn_reset">重置</el-button>
						</el-form-item>
					</el-col>

				<el-col :xs="24" :sm="12" :lg="12" class="search_btn_2">
					<el-form-item>
						<el-button type="success" class="float-right" @click="exportExcel()" style="margin-right: 10px;">导出Excel</el-button>
						<el-button type="warning" class="float-right" @click="exportCSV()" style="margin-right: 10px;">导出CSV</el-button>
						<el-button v-if="user_group == '管理员' || $check_action('/praise/table','del')" class="float-right search_btn_del" type="danger" @click="delInfo()">删除</el-button>
					</el-form-item>
				</el-col>
				</el-col>
			</el-row>
		</el-form>
		
		<!-- 数据表格 -->
		<el-table border :data="list" @selection-change="selectionChange" @sort-change="$sortChange" style="width: 100%" stripe>
			<el-table-column fixed type="selection" tooltip-effect="dark" width="50">
			</el-table-column>

			<el-table-column prop="user_id" label="用户ID" min-width="100">
			</el-table-column>

			<el-table-column prop="source_table" label="来源表" min-width="100">
			</el-table-column>

			<el-table-column prop="source_id" label="来源ID" min-width="100">
			</el-table-column>

			<el-table-column prop="status" label="状态" min-width="100">
				<template slot-scope="scope">
					<el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
						{{ scope.row.status == 1 ? '已点赞' : '已取消' }}
					</el-tag>
				</template>
			</el-table-column>

			<el-table-column sortable prop="create_time" label="创建时间" min-width="200">
			    <template slot-scope="scope">
			        {{ $toTime(scope.row["create_time"],"yyyy-MM-dd hh:mm:ss") }}
			    </template>
			</el-table-column>

			<el-table-column sortable prop="update_time" label="更新时间" min-width="200">
			    <template slot-scope="scope">
			        {{ $toTime(scope.row["update_time"],"yyyy-MM-dd hh:mm:ss") }}
			    </template>
			</el-table-column>
		</el-table>

		<!-- 分页器 -->
		<div class="mt text_center">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="query.page"
			 :page-sizes="[7, 10, 30, 100]" :page-size="query.size" layout="total, sizes, prev, pager, next, jumper" :total="count">
			</el-pagination>
		</div>
		<!-- /分页器 -->
	</el-main>
</template>

<script>
	import mixin from "@/mixins/page.js";
	import LineChart from "@/components/charts/new_line_chart.vue";
	import PieChart from "@/components/charts/pie_chart.vue";

	export default {
		mixins: [mixin],
		components: {
			LineChart,
			PieChart
		},
		data() {
			return {
				// 获取数据地址
				url_get_list: "~/api/praise/get_list?like=0",
				url_del: "~/api/praise/del?",

				// 字段ID
				field:"praise_id",

				// 查询
				query: {
					size: 10,
					page: 1,
					user_id: "",
					date_range: []
				},

				// 数据
				list: [],
				
				// 图表数据
				praiseTrendData: {
					xAxis: []
				},
				praiseTrendSeries: [],
				praiseStatusData: [],
				// 排行榜数据
				praiseRanking: []
			}
		},
		methods: {
			deleteRow(index, rows) {
				rows.splice(index, 1);
			},

			table_class({row, column, rowIndex, columnIndex}){
				return "table_class";
			},
			
			/**
			 * 查询前处理，转换日期范围参数
			 */
			get_list_before(param) {
				// 处理日期范围
				if (param.date_range && Array.isArray(param.date_range) && param.date_range.length === 2) {
					param.create_time_min = param.date_range[0] + ' 00:00:00';
					param.create_time_max = param.date_range[1] + ' 23:59:59';
					delete param.date_range;
				}
				return param;
			},
			
			/**
			 * 处理列表数据，更新图表
			 */
			processChartData() {
				this.processTrendData(); // 从后端获取趋势数据
				this.processStatusData(); // 从后端获取状态分布数据
				this.processRanking(); // 从后端获取排行榜数据
			},
			
			/**
			 * 处理趋势数据（从后端获取）
			 */
			async processTrendData() {
				try {
					// 从后端获取趋势统计数据
					const res = await this.$get("~/api/praise/trend_statistics?", {});
					if (res.result && res.result.list) {
						const trendData = res.result.list;
						const dates = trendData.map(item => item.date);
						const values = trendData.map(item => item.count);
						
						// new_line_chart组件期望的数据格式：
						// vm.xAxis - x轴数据数组（时间点）
						// vm.names - 系列名称数组
						// vm.values - 二维数组，每个子数组是一个时间点的所有系列的值
						// 例如：values = [[1], [2], [3], [4], [5], [6], [7]] 表示7个时间点，每个时间点有1个系列的值
						const valuesByTime = values.map(v => [v]); // 将每个值转换为数组，因为只有1个系列
						
						this.praiseTrendData = {
							xAxis: dates,
							names: ['点赞数量'],
							values: valuesByTime // 二维数组，每个子数组是一个时间点的所有系列的值
						};
						
						// 保留series用于其他用途（如果需要）
						this.praiseTrendSeries = [{
							name: '点赞数量',
							type: 'line',
							smooth: true,
							data: values,
							itemStyle: {
								color: '#67C23A'
							},
							areaStyle: {
								color: {
									type: 'linear',
									x: 0,
									y: 0,
									x2: 0,
									y2: 1,
									colorStops: [{
										offset: 0, color: 'rgba(103, 194, 58, 0.3)'
									}, {
										offset: 1, color: 'rgba(103, 194, 58, 0.1)'
									}]
								}
							}
						}];
					} else {
						this.praiseTrendData = { 
							xAxis: [],
							names: [],
							values: []
						};
						this.praiseTrendSeries = [];
					}
				} catch (error) {
					console.error('获取点赞趋势统计数据失败:', error);
					this.praiseTrendData = { 
						xAxis: [],
						names: [],
						values: []
					};
					this.praiseTrendSeries = [];
				}
			},
			
			/**
			 * 处理状态分布数据（从后端获取）
			 */
			async processStatusData() {
				try {
					// 从后端获取状态分布统计数据
					const res = await this.$get("~/api/praise/status_statistics?", {});
					if (res.result && res.result.list) {
						this.praiseStatusData = res.result.list;
					} else {
						this.praiseStatusData = [
							{ name: '已点赞', value: 0 },
							{ name: '已取消', value: 0 }
						];
					}
				} catch (error) {
					console.error('获取点赞状态分布统计数据失败:', error);
					this.praiseStatusData = [
						{ name: '已点赞', value: 0 },
						{ name: '已取消', value: 0 }
					];
				}
			},
			
			/**
			 * 处理点赞排行榜（从后端获取）
			 */
			async processRanking() {
				try {
					// 从后端获取排行榜数据
					const res = await this.$get("~/api/praise/ranking?", {});
					if (res.result && res.result.list) {
						this.praiseRanking = res.result.list;
					} else {
						this.praiseRanking = [];
					}
				} catch (error) {
					console.error('获取点赞排行榜失败:', error);
					this.praiseRanking = [];
				}
			},
			
			/**
			 * 格式化日期
			 */
			formatDate(date) {
				if (typeof date === 'string') {
					date = new Date(date);
				}
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			
			/**
			 * 导出Excel
			 */
			async exportExcel() {
				try {
					this.$message.info('正在导出Excel...');
					
					const allData = await this.getAllData();
					let XLSX;
					try {
						XLSX = require('xlsx');
					} catch (e) {
						// 如果 require 失败，尝试动态导入
						XLSX = await import('xlsx');
					}
					
					const exportData = allData.map((item, index) => ({
						'序号': index + 1,
						'点赞ID': item.praise_id || '',
						'用户ID': item.user_id || '',
						'来源表': item.source_table || '',
						'来源ID': item.source_id || '',
						'状态': item.status == 1 ? '已点赞' : '已取消',
						'创建时间': this.$toTime(item.create_time, "yyyy-MM-dd hh:mm:ss") || '',
						'更新时间': this.$toTime(item.update_time, "yyyy-MM-dd hh:mm:ss") || ''
					}));
					
					const wb = XLSX.utils.book_new();
					const ws = XLSX.utils.json_to_sheet(exportData);
					XLSX.utils.book_append_sheet(wb, ws, "点赞数据");
					
					const fileName = `点赞数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
					XLSX.writeFile(wb, fileName);
					
					this.$message.success('导出成功！');
				} catch (error) {
					console.error('导出Excel失败:', error);
					this.$message.error('导出失败，请重试');
				}
			},
			
			/**
			 * 导出CSV
			 */
			async exportCSV() {
				try {
					this.$message.info('正在导出CSV...');
					
					const allData = await this.getAllData();
					
					const headers = ['序号', '点赞ID', '用户ID', '来源表', '来源ID', '状态', '创建时间', '更新时间'];
					let csvContent = headers.join(',') + '\n';
					
					allData.forEach((item, index) => {
						const row = [
							index + 1,
							item.praise_id || '',
							item.user_id || '',
							item.source_table || '',
							item.source_id || '',
							item.status == 1 ? '已点赞' : '已取消',
							this.$toTime(item.create_time, "yyyy-MM-dd hh:mm:ss") || '',
							this.$toTime(item.update_time, "yyyy-MM-dd hh:mm:ss") || ''
						];
						csvContent += row.join(',') + '\n';
					});
					
					const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
					const link = document.createElement('a');
					const url = URL.createObjectURL(blob);
					link.setAttribute('href', url);
					link.setAttribute('download', `点赞数据_${new Date().toISOString().slice(0, 10)}.csv`);
					link.style.visibility = 'hidden';
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
					
					this.$message.success('导出成功！');
				} catch (error) {
					console.error('导出CSV失败:', error);
					this.$message.error('导出失败，请重试');
				}
			},
			
			/**
			 * 获取所有数据（不分页）
			 */
			async getAllData() {
				const query = Object.assign({}, this.query);
				query.size = 10000;
				query.page = 1;
				
				if (query.date_range && query.date_range.length === 2) {
					query.create_time_min = query.date_range[0] + ' 00:00:00';
					query.create_time_max = query.date_range[1] + ' 23:59:59';
					delete query.date_range;
				}
				
				// 使用 $get 方法，它会自动处理 ~/ 符号
				const json = await this.$get(this.url_get_list, query);
				if (json.result && json.result.list) {
					return json.result.list;
				}
				return [];
			}
		},
		mounted() {
			// 确保数据从后端获取
			this.get_list();
			// 初始化图表（从后端获取数据，不依赖list）
			this.processChartData();
		}
	}
</script>

<style type="text/css">
	.bar_chart, .line_chart, .pie_chart {
		width: 100%;
		height: 300px;
	}
</style>